package com.bumptech.glide.load.resource.bitmap;

import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.ResourceDecoder;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.util.Util;
import ohos.media.image.PixelMap;
import org.jetbrains.annotations.NotNull;

/**
 * Passes through a (hopefully) non-owned {@link Bitmap} as a {@link Bitmap} based {@link Resource}
 * so that the given {@link Bitmap} is not recycled.
 */
public final class UnitBitmapDecoder implements ResourceDecoder<PixelMap, PixelMap> {

  @Override
  public boolean handles(@NotNull PixelMap source, @NotNull Options options) {
    return true;
  }

  @Override
  public Resource<PixelMap> decode(
      @NotNull PixelMap source, int width, int height, @NotNull Options options) {

    return new NonOwnedBitmapResource(source);
  }

  private static final class NonOwnedBitmapResource implements Resource<PixelMap> {

    private final PixelMap pixelmap;

    NonOwnedBitmapResource(@NotNull PixelMap pixelmap) {
      this.pixelmap = pixelmap;
    }

    @NotNull
    @Override
    public Class<PixelMap> getResourceClass() {
      return PixelMap.class;
    }

    @NotNull
    @Override
    public PixelMap get() {
      return pixelmap;
    }

    @Override
    public int getSize() {
      return Util.getBitmapByteSize(pixelmap);
    }

    @Override
    public void recycle() {
      // Do nothing.
    }
  }
}
